package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Brand;
import com.spzx.product.domain.CategoryBrand;
import com.spzx.product.mapper.BrandMapper;
import com.spzx.product.mapper.CategoryBrandMapper;
import com.spzx.product.service.ICategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 分类品牌 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements ICategoryBrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<CategoryBrand> selectCategoryBrandList() {
        return baseMapper.selectCategoryBrandList();
    }

    @Override
    public void saveCategoryBrand(CategoryBrand categoryBrand) {
        //先判断是否存在分类品牌，根据品牌ID+分类ID，存在则抛出异常
        LambdaQueryWrapper<CategoryBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryBrand::getBrandId, categoryBrand.getBrandId())
                .eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId());
        long count = count(queryWrapper);
        if (count > 0) {
            throw new ServiceException("分类品牌已存在");
        }
        //判断没有后执行新增的业务逻辑
        categoryBrand.setCreateBy(SecurityUtils.getUsername());
        baseMapper.insert(categoryBrand);
    }

    @Override
    public List<Brand> brandList(Long categoryId) {
        return baseMapper.brandList(categoryId);
    }

    /*@Override
    public List<Brand> brandList(Long categoryId) {
        List<CategoryBrand> list = list(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getCategoryId, categoryId).select(CategoryBrand::getBrandId));
        if (!CollectionUtils.isEmpty(list)) {
            //第一种方式：使用wrapper查询

            //采用Stream流的形式获取
            *//*list.stream().map(CategoryBrand::getBrandId)
                    .collect(Collectors.toList());
            *//*

            //List<Long>中的Long类型是根据返回值类型生成的，collect(Collectors.toList());的意思是收集流中的数据
            *//*List<Long> brandIdList = list.stream().map(categoryBrand -> {

                return categoryBrand.getBrandId();
            }).collect(Collectors.toList());
            *//*

            //再次简化
            List<Long> brandIdList = list.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
            //根据品牌Id列表查询品牌列表
            List<Brand> brands = brandMapper.selectBatchIds(brandIdList);
            return brands;
        }
        return null;
    }*/



}
